package org.zsqx.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.zsqx.bean.PointsExcel;
import org.zsqx.bean.RainReportExcel;
import org.zsqx.bean.WarnSet;
import org.zsqx.bean.ZdzHoursDataRealt;
import org.zsqx.dao.ZdzReportDAOImpl;
import org.zsqx.dao.ZdzReportDao;
import org.zsqx.tools.ExcelTools;
import org.zsqx.tools.OrderByBean;
import org.zsqx.tools.PropertiesTools;

@Action(value="/zdzReportAction",results={
		@Result(name="reports",location="/login/zdzReports.jsp"),
		@Result(name="disasterWarning",location="/login/disasterWarning.jsp"),
		@Result(name="warnpage",location="/login/system/warnSetting.jsp"),
		@Result(name="warnDisasterSettingPage",location="/login/system/warnDisasterSettingPage.jsp"),
		@Result(name="warnSignalSettingPage",location="/login/system/warnSignalSettingPage.jsp"),
		@Result(name="warnZmlSettingPage",location="/login/system/warnZmlSettingPage.jsp"),
		@Result(name="outputExcel",type="stream",params={"contentType","application/vnd.ms-excel","bufferSize","2046","inputName","excelStream","contentDisposition","attachment;filename=${fileNames}"}),
		@Result(name="input",location="/error.jsp")
})
public class ZdzReportAction extends BaseAction{
	public final static String THREE_MONTH_TABLE = "zdz_hours_data_realTime";
	public final static String TOTAL_TABLE = "zdz_hours_data";
	public static String orderByField;
	protected WarnSet warnSet;
	protected ZdzReportDao zdzDao = new ZdzReportDAOImpl();
	private String reportTitle;
	private String report_type;
	protected String date;
	private String startTime;
	private String endTime;
	protected Integer hour;
	protected Integer minute;
	private Integer startHour;
	private Integer endHour;
	protected Map<Integer,String> hourMap;
	protected Map<Integer,String> minuteMap;
	private List<ZdzHoursDataRealt> zdzList;
	private static List<ZdzHoursDataRealt> zdzListTemp;
	private OrderByBean orderByBean;
	private String[] zdzType;
	private String ztype;
	private InputStream excelStream;
	private String fileNames;
//	private String timestage;
//	private String orderfield;
//	private String ordertype;
	
	public String reportTemp(){
		report_type = "reports_temp";
		String datetime = rightDatetime();
		zdzList = zdzDao.tempReport(datetime,orderByBean);
		reportTitle = datetime+"温度";
		setHourValue();
		return "reports";
	}
	public String reportTempPrev(){
		minute = minute-5;
		if(minute<0){
			minute=55;
			hour-=1;
		}
		return reportTemp();
	}
	public String reportTempNext(){
		minute = minute+5;
		if(minute==60){
			minute = 0;
			hour+=1;
		}
		return reportTemp();
	}
	public String reportRain(){
		report_type = "reports_rain";
		String datetime = rightDatetime();
		zdzList = zdzDao.rainReport(datetime,orderByBean);
		reportTitle = datetime+"雨量";
		setHourValue();
		return "reports";
	}
	public String reportRainPrev(){
		minute = minute-5;
		if(minute<0){
			minute=55;
			hour-=1;
		}
		return reportRain();
	}
	public String reportRainNext(){
		minute = minute+5;
		if(minute==60){
			minute = 0;
			hour+=1;
		}
		return reportRain();
	}
	public String reportWind(){
		report_type = "reports_wind";
		String datetime = rightDatetime();
		zdzList = zdzDao.windReport(datetime,orderByBean);
		reportTitle = datetime+"风速";
		setHourValue();
		return "reports";
	}
	public String reportWindPrev(){
		minute = minute-5;
		if(minute<0){
			minute=55;
			hour-=1;
		}
		return reportWind();
	}
	public String reportWindNext(){
		minute = minute+5;
		if(minute==60){
			minute = 0;
			hour+=1;
		}
		return reportWind();
	}
	public String reportHumidity(){
		report_type = "reports_humidity";
		String datetime = rightDatetime();
		zdzList = zdzDao.humidityReport(datetime,orderByBean);
		reportTitle = datetime+"相对湿度";
		setHourValue();
		return "reports";
	}
	public String reportHumidityPrev(){
		minute = minute-5;
		if(minute<0){
			minute=55;
			hour-=1;
		}
		return reportHumidity();
	}
	public String reportHumidityNext(){
		minute = minute+5;
		if(minute==60){
			minute = 0;
			hour+=1;
		}
		return reportHumidity();
	}
	public String reportPressure(){
		report_type = "reports_pressure";
		String datetime = rightDatetime();
		zdzList = zdzDao.pressureReport(datetime,orderByBean);
		reportTitle = datetime+"气压";
		setHourValue();
		return "reports";
	}
	public String reportPressurePrev(){
		minute = minute-5;
		if(minute<0){
			minute=55;
			hour-=1;
		}
		return reportPressure();
	}
	public String reportPressureNext(){
		minute = minute+5;
		if(minute==60){
			minute = 0;
			hour+=1;
		}
		return reportPressure();
	}
	
	//区间雨量
	public String reportRainhour() throws ParseException{
		report_type = "reports_rainhour";
		ztype = "";
		if(zdzType!=null&&zdzType.length>0){
			for (int i = 0; i < zdzType.length; i++) {
				zdzType[i]="'"+zdzType[i]+"'";
				if(i!=zdzType.length-1){
					ztype += zdzType[i]+",";
				}else{
					ztype += zdzType[i];
				}
			}
		}else{
			ztype = "'镇区','水库水闸','学校'";
		}
		
		if(null==startTime){
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			DateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			endTime = dateFormat.format(calendar.getTime());
			calendar.add(Calendar.HOUR_OF_DAY, -3);
			startTime = dateFormat.format(calendar.getTime());
		}
		zdzList = zdzDao.severalReport(startTime, endTime,ztype,orderByBean);
		zdzListTemp=zdzList;
		//for (int i = 0; i < zdzList.size(); i++) {
			//System.out.println(zdzList.get(i));
		//}
//		if(ztype==null)ztype="'镇区','水库水闸','学校'";
		reportTitle = startTime+"至"+endTime+"点"+ztype+"雨量";
		setHourValue();
		return "reports";
	}
	public String outputExcel(){
		return "outputExcel";
	}
	//最近3小时雨量
	public String reportRainLeastHour(){
		report_type = "reports_rainhour";
		if(hour==3){
			zdzList = zdzDao.pastThreeHourReport(hour,orderByBean);
		}
		if(hour==24){
			zdzList = zdzDao.pastTwentyFourHourReport(hour,orderByBean);
		}
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		DateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		endTime = dateFormat.format(calendar.getTime());
		calendar.add(Calendar.HOUR_OF_DAY, -hour);
		startTime = dateFormat.format(calendar.getTime());
		reportTitle = startTime+"至"+endTime+"点'镇区','水库水闸','学校'雨量";
		return "reports";
	}
	protected String rightDatetime(){
		Calendar calendar = Calendar.getInstance();
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZdzReportDAOImpl zd = new ZdzReportDAOImpl();
		Date lastDate = zd.zdLastDate();
		String datetime = "";
		if(null!=date){
			DateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date day = dateFormat.parse(date);
				calendar.setTime(day);
				calendar.set(Calendar.HOUR_OF_DAY, hour);
				calendar.set(Calendar.MINUTE, minute);
				calendar.set(Calendar.SECOND, 0);
				Date nowHourTime = calendar.getTime();
				datetime = sdf.format(nowHourTime);
			} catch (ParseException e) {
				System.out.println("日期格式转换错误");
				e.printStackTrace();
			}
		}else{
			datetime = sdf.format(lastDate);
			calendar.setTime(lastDate);
			date = calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(calendar.DAY_OF_MONTH);
			hour = calendar.get(Calendar.HOUR_OF_DAY);
			minute = calendar.get(Calendar.MINUTE);
		}
		return datetime;
	}
	//预警值设置
	public String warnSettingPage(){
		PropertiesTools pt = new PropertiesTools();
		warnSet = (WarnSet) pt.getPropertyesBean(new WarnSet());
		return "warnpage";
	}
	public String warnSetting(){
		PropertiesTools pt = new PropertiesTools();
		pt.setPropertiesBean(warnSet);
		return warnSettingPage();
	}
	/*flex加载背景图片*/
	public void loadImage(){
		ZdzReportDAOImpl zd = new ZdzReportDAOImpl();
		String shareDirectoryName = zd.getZdzBg();
		if(shareDirectoryName!=null){
			String host = "172.22.42.249";// 需要访问的主机host
			String username = "aa";// 访问用户
			String password = "aa";// 密码
			String path = "\\\\" + host + "\\" + shareDirectoryName;// 访问路径
			BufferedOutputStream bos = null;
			BufferedInputStream bis = null;
			try {
				Runtime runtime = Runtime.getRuntime();
				String command = "net use " + path + " " + " /delete";
				Process p = runtime.exec(command);
				command = "net use " + path + " " + password + " /" + "user:"+ username;
				p = runtime.exec(command);
				bis = new BufferedInputStream(new FileInputStream(shareDirectoryName));
				bos = new BufferedOutputStream(response.getOutputStream());
				byte[] buff = new byte[2048];
				int bytesRead;
	
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (bis != null)
						bis.close();
					if (bos != null) {
						bos.flush();
						bos.close();
						bos = null;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		try {
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public String getReport_type() {
		return report_type;
	}
	public void setReport_type(String reportType) {
		report_type = reportType;
	}
	public Integer getHour() {
		return hour;
	}
	public void setHour(Integer hour) {
		this.hour = hour;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public List<ZdzHoursDataRealt> getZdzList() {
		return zdzList;
	}
	public void setZdzList(List<ZdzHoursDataRealt> zdzList) {
		this.zdzList = zdzList;
	}
	public Map<Integer, String> getHourMap() {
		return hourMap;
	}
	public void setHourMap(Map<Integer, String> hourMap) {
		this.hourMap = hourMap;
	}
	public String getReportTitle() {
		return reportTitle;
	}
	public void setReportTitle(String reportTitle) {
		this.reportTitle = reportTitle;
	}
	
	public Integer getStartHour() {
		return startHour;
	}
	public void setStartHour(Integer startHour) {
		this.startHour = startHour;
	}
	public Integer getEndHour() {
		return endHour;
	}
	public void setEndHour(Integer endHour) {
		this.endHour = endHour;
	}
	public WarnSet getWarnSet() {
		return warnSet;
	}
	public void setWarnSet(WarnSet warnSet) {
		this.warnSet = warnSet;
	}
	public String getStartTime() {
		return startTime;
	}
	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}
	public String getEndTime() {
		return endTime;
	}
	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}
	protected void setHourValue(){
		hourMap = new HashMap<Integer,String>();
		for (int i = 1; i <= 24; i++) {
			hourMap.put(i, i+"点");
		}
		minuteMap = new HashMap<Integer, String>();
		for (int i = 0; i <= 60; i+=5){
			minuteMap.put(i, i+"分");
		}
	}
	public OrderByBean getOrderByBean() {
		return orderByBean;
	}
	public void setOrderByBean(OrderByBean orderByBean) {
		this.orderByBean = orderByBean;
	}
	public Integer getMinute() {
		return minute;
	}
	public void setMinute(Integer minute) {
		this.minute = minute;
	}
	public Map<Integer, String> getMinuteMap() {
		return minuteMap;
	}
	public void setMinuteMap(Map<Integer, String> minuteMap) {
		this.minuteMap = minuteMap;
	}
	
	public String[] getZdzType() {
		return zdzType;
	}
	public void setZdzType(String[] zdzType) {
		this.zdzType = zdzType;
	}
	public String getZtype() {
		return ztype;
	}
	public void setZtype(String ztype) {
		this.ztype = ztype;
	}
	
	public InputStream getExcelStream() {
		String absolute_path=request.getRealPath("/");
		Map<String, String> map=new HashMap<String, String>();
		map.put("id", "编号");
		map.put("zdz_Name", "镇区");
		map.put("dayrf", "雨量");
		map.put("wd10maxdf", "最大风速");
		map.put("wd3smaxdf", "极大风速");
//		System.out.println(startTime+endTime+orderByBean.getOrderByFile()+orderByBean.getOrderByMethod());
		List<RainReportExcel> excelList=new ArrayList<RainReportExcel>();
		for (ZdzHoursDataRealt z: this.zdzListTemp) {
			RainReportExcel rre=new RainReportExcel();
			rre.setId(z.getId());
			rre.setZdz_Name(z.getZdzName());
			rre.setDayrf(z.getDayrf());
			rre.setWd10maxdf(z.getWd10maxdf());
			rre.setWd3smaxdf(z.getWd3smaxdf());
			excelList.add(rre);
		}
		InputStream in=null;
		if (excelList.size()>0) {
			try {
				fileNames=ExcelTools.writeToExcel("风雨报表", absolute_path,excelList, map)+".xls";
				String realPath="/login/excel/"+fileNames;
				in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
				if(null==in){
					System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");   
				}
			}catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (RowsExceededException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NullPointerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WriteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(null!=in){
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
		}
		return in;
	}
	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
	
	public String getFileNames() {
		return fileNames;
	}
	public void setFileNames(String fileNames) {
		this.fileNames = fileNames;
	}
	
	
//	public String getTimestage() {
//		return timestage;
//	}
//	public void setTimestage(String timestage) {
//		this.timestage = timestage;
//	}
//	public String getOrderfield() {
//		return orderfield;
//	}
//	public void setOrderfield(String orderfield) {
//		this.orderfield = orderfield;
//	}
//	
//	public String getOrdertype() {
//		return ordertype;
//	}
//	public void setOrdertype(String ordertype) {
//		this.ordertype = ordertype;
//	}
	@Override
	public void validate() {
		WarnReportAction.ws = null;
		if(orderByBean!=null){
			if(null!=orderByBean.getOrderByMethod()&&null!=orderByBean.getOrderByFile()&&orderByField.equals(orderByBean.getOrderByFile())){
				if(orderByBean.getOrderByMethod().equals("asc")){
					orderByBean.setOrderByMethod("desc");
				}else{
					orderByBean.setOrderByMethod("asc");
				}
			}else{
				orderByBean.setOrderByMethod("desc");
			}
		}else{
			orderByBean = new OrderByBean();
			orderByBean.setOrderByFile("id");
			orderByBean.setOrderByMethod("asc");
		}
		orderByField=orderByBean.getOrderByFile();
		super.validate();
	}
	

}
